#include "ast.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *name;
    int value;
} Variable;

Variable variables[100];
int var_count = 0;

int find_var(char *name) {
    for (int i = 0; i < var_count; i++) {
        if (strcmp(variables[i].name, name) == 0) {
            return variables[i].value;
        }
    }
    return 0; // 默认返回0
}

void set_var(char *name, int value) {
    for (int i = 0; i < var_count; i++) {
        if (strcmp(variables[i].name, name) == 0) {
            variables[i].value = value;
            return;
        }
    }
    variables[var_count].name = strdup(name);
    variables[var_count].value = value;
    var_count++;
}

int interpret(ASTNode *node) {
    if (!node) return 0;
    
    switch (node->type) {
        case NUM_NODE:
            return node->num;
        case VAR_NODE:
            return find_var(node->var_name);
        case OP_NODE:
            switch (node->op.op) {
                case '+': 
                    return interpret(node->op.left) + interpret(node->op.right);
                case '=': {
                    int val = interpret(node->op.right);
                    set_var(node->op.left->var_name, val);
                    return val;
                }
            }
        case PRINT_NODE: {
            int val = interpret(node->expr);
            printf("%d\n", val);
            return val;
        }
        default:
            return 0;
    }
}